import { Toast } from 'antd-mobile'
import axios from 'axios'
import { getTokenInfo, setTokenInfo } from './storage'
import history from './history'
import store from '@/store'
import { onlogout, saveToken } from '@/store/action/login'
const baseURL = 'http://toutiao.itheima.net/v1_0'
const http = axios.create({
  baseURL,
  timeout: 5000,
})

// 请求拦截器
http.interceptors.request.use((config) => {
  const token = getTokenInfo().token
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
})

// 响应拦截器
http.interceptors.response.use(
  (response) => {
    return response.data
  },
  async (error) => {
    if (!error.response) {
      Toast.info('网络超时')
      return Promise.reject(error)
    }
    const { response, config } = error
    console.log(error)
    if (response.status !== 401) {
      const { response } = error
      Toast.info(response.data.message)
      return Promise.reject(error)
    }
    const { refresh_token } = getTokenInfo()
    if (!refresh_token) {
      history.push({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      return Promise.reject(error)
    }
    try {
      const res = await axios({
        method: 'put',
        url: baseURL + '/authorizations',
        headers: {
          Authorization: 'Bearer ' + refresh_token,
        },
      })
      const tokenInfo = {
        token: res.data.data.token,
        refresh_token: refresh_token,
      }
      store.dispatch(saveToken(tokenInfo))
      setTokenInfo(tokenInfo)
      return http(config)
    } catch {
      store.dispatch(onlogout())
      history.push({
        pathname: '/login',
        state: {
          from: history.location.pathname,
        },
      })
      Toast.info('登录过期,请重新登录')
      return Promise.reject(error)
    }
  }
)
export default http
